/**
 * 
 */
package sk.stuba.fiit.foo07.genex.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 * @author _mizu_
 * 
 */
public class PictureComponent extends JPanel {

    /**
     * 
     */
    private static final long serialVersionUID = 216961397493029305L;
    private Image orig;
    private Image scaled;
    private Image actual;
    private boolean isScaled = true;

    public void setImage(byte[] content) {
        MediaTracker mt = new MediaTracker(this);

        orig = new ImageIcon(content).getImage();
        float w = getMinimumSize().width;
        float h = getMinimumSize().height;
        float ow = orig.getWidth(null);
        float oh = orig.getHeight(null);
        float faktor;

        faktor = ow / oh;
        if (faktor > 1.0)
            h /= faktor;
        else
            w *= faktor;

        scaled = orig.getScaledInstance(Math.round(w), Math.round(h),
                Image.SCALE_SMOOTH);

        mt.addImage(orig, 0);
        mt.addImage(scaled, 1);
        try {
            mt.waitForAll();
        } catch (Exception e) {
        }

        setActualSize();
    }

    public void setScaled(boolean val) {
        isScaled = val;
        setActualSize();
    }

    private void setActualSize() {
        if (isScaled)
            actual = scaled;
        else
            actual = orig;

        if (actual != null)
            setPreferredSize(new Dimension(actual.getWidth(null), actual
                    .getHeight(null)));
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getBounds().width, getBounds().height);
        if (actual != null) {
            g.drawImage(actual, 0, 0, null);
            g.setColor(Color.RED);
            String toDraw = "" + orig.getWidth(null) + "x"
                    + orig.getHeight(null);
            g.drawString(toDraw, 3, 12);
        }
    }
}
